﻿Imports System.Windows.Forms
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Xml.Serialization
Imports System.Threading
Imports System.Net
Public Class frmRun
    Private DosCommandOutput As DosCommand.DosCommandOutput '执行Dos程序类
    Private m_RusSucess As Boolean = False '用于判断程序是否运行成功的标志
    Private SurfFileName As String '用于临时储存文件名
    Private ProfFileName As String '用于临时储存文件名

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRun.Click
        Dim frmM As frmMain
        frmM = My.Application.ApplicationContext.MainForm
        '创建项目的文件夹------------------------------------------------------------------
        frmM.CreateProjectFlod(AermodProject0.SaveName, False)

#Const NOISEVALUE = "正式版"
#If NOISEVALUE = "正式版" Then
        '重新编写注册码

        Dim bRet As Boolean

        Dim info As String

        Dim RealLen As Integer
        Dim tBuf() As Byte
        ReDim tBuf(8)

        Dim edc As ELE_DEVICE_CONTEXT

        edc.ulSize = Len(edc)

        'open device
        bRet = EleOpenFirstDevice(0, 0, 0, ELE_SHARE_MODE, edc)
        If bRet Then
            info = "访问加密锁"
            'set led down
            bRet = EleControl(edc, ELE_SET_LED_DOWN, 0, 0, 0, 0, RealLen)
            If bRet Then
                info = "set led down success"
            Else

            End If

            Dim sIn As String
            Dim Output(1023) As Byte

            sIn = ""
            info = "" & sIn
            bRet = EleExecute(edc, "gg", sIn, Len(sIn), Output(0), 1024, RealLen)
            '在这里分析读取的加密数据
            Dim A0 As Byte = Output(0)
            Dim A1 As Byte = Output(1)
            Dim A2 As Byte = Output(2)
            Dim A3 As Byte = Output(3)
            Dim A4 As Byte = Output(4)
            Dim A5 As Byte = Output(5)
            Dim A6 As Byte = Output(6)
            Dim A7 As Byte = Output(7)
            Dim A8 As Byte = Output(8)
            Dim A9 As Byte = Output(9)

            If A0 <> 42 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A1 <> 13 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A2 <> 8 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A3 <> 28 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A4 <> 92 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A5 <> 21 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A6 <> 12 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A7 <> 52 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A8 <> 92 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            If A9 <> 86 Then
                MessageBox.Show("对不起，请检查您插入的加密锁是否为正版授权的加密锁！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
            'set led up
            bRet = EleControl(edc, ELE_SET_LED_UP, 0, 0, 0, 0, RealLen)
            If bRet Then
                info = "set led up success"
            Else
                MessageBox.Show("不能正确访问加密锁，请检查是否已经插入加密锁。", "访问加密锁失败", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
            'close device
            bRet = EleClose(edc)
            If bRet Then
                info = "close device success"
            Else
                MessageBox.Show("不能正确访问加密锁，请检查是否已经插入加密锁。", "访问加密锁失败", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
        Else
            MessageBox.Show("不能正确访问加密锁，请检查是否已经插入加密锁。", "访问加密锁失败", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If
#End If



        Me.TextBox1.Text = ""
        '-----------------------------------------------------------
        '对城市选项进行检查
        '-----------------------------------------------------------
        If AermodProject0.Aermod.Control.Urbans.UrbanOpt = True Then
            Dim IsUrbans As Boolean = False
            For i As Integer = 0 To AermodProject0.Aermod.Source.PointSources.PointSource.Length - 1
                If AermodProject0.Aermod.Source.PointSources.PointSource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.VolumeSources.VolumeSource.Length - 1
                If AermodProject0.Aermod.Source.VolumeSources.VolumeSource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.AreaSources.AreaSource.Length - 1
                If AermodProject0.Aermod.Source.AreaSources.AreaSource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.AreacircSources.AreaCircSource.Length - 1
                If AermodProject0.Aermod.Source.AreacircSources.AreaCircSource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.AreaPolySources.AreaPolySource.Length - 1
                If AermodProject0.Aermod.Source.AreaPolySources.AreaPolySource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.LineSources.ArrayLineSources.Length - 1
                If AermodProject0.Aermod.Source.LineSources.ArrayLineSources(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            For i As Integer = 0 To AermodProject0.Aermod.Source.OpenPitSources.OpenPitSource.Length - 1
                If AermodProject0.Aermod.Source.OpenPitSources.OpenPitSource(i).Urbansrc.UrbanOpt = True Then
                    IsUrbans = True
                    Exit For
                End If
            Next
            If IsUrbans = False Then
                MessageBox.Show("您的方案中考虑了城市影响，请至少在1个污染源中设置所在城市")
                Exit Sub
            End If
        End If

        m_RusSucess = False '程序运行成功的标志
        '先保存文件
        'SaveAs(False)



        Me.cmdRun.Enabled = False
        Me.cmdStop.Enabled = True
        '打开时钟
        Timer1.Start()

        Me.Status.Text = "正在计算"
        Me.ProgressBar.Visible = True
        If BackgroundWorkerAermod.IsBusy Then
            '程序正在进行上一个计算，请稍候再计算
            MsgBox("程序正在进行上一个计算，请稍候再计算")
        Else
            '先将控制制流文件改名为Aermod.inp

            If AermodProject0.Aermod IsNot Nothing Then
                '将所有的文件均复制在AERMOD.ext的目录下，并根据复制后的结果修改aemod.inp文件
                Me.cmdRun.Enabled = False
                BackgroundWorkerAermod.RunWorkerAsync() '执行后台程序
            Else
                MessageBox.Show("项目为空，请新建一个项目!", "项目为空", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End If
    End Sub

   

    Private Sub chkRunAermap_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkRunAermap.CheckedChanged
        AermodProject0.Aermap.Run = chkRunAermap.Checked
    End Sub

    Private Sub frmRun_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        StopProcess() '终止DOS程序进程
    End Sub

    Private Sub frmRun_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub BackgroundWorkerAermod_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorkerAermod.DoWork
        
        If chkRunAermet.Checked = True Then
            Me.RunAermet() '气象预处理
        End If

        Me.RunBpipprm() '建筑物下洗
        '--------------------------------------------------------------------------------------
        '运行地形 
        '--------------------------------------------------------------------------------------
        If chkRunAermap.Checked = True Then
            If AermodProject0.Aermap.Control.DataFile.Length > 0 And AermodProject0.Aermod.Control.AllPolluts.GenralPolluts.ArrayPollut(0).Dispersion.Flat = False _
                          And AermodProject0.Aermap.Run = True Then
                If RunAermap() = False Then
                    MsgBox("地形处理程序出错，请重新设置地形数据参数!")
                    Exit Sub
                End If
            End If
        End If
        If Me.chkRunAermod.Checked = True Then
            RunAermodProject() '运行Aermod的方案
        End If
        m_RusSucess = True  '程序运行成功的标志
    End Sub

    Private Sub BackgroundWorkerAermod_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorkerAermod.ProgressChanged
        'Me.progressBar1.Value = e.ProgressPercentage
    End Sub
    ''' <summary>
    ''' 运行建筑物下洗程序
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RunBpipprm()
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)

        '-------------------------------------------------------------------------------------
        '运行建筑物下洗程序
        '-------------------------------------------------------------------------------------
        If AermodProject0.Aermod.Control.AllPolluts.GenralPolluts.ArrayPollut(0).Dispersion.NoStd = False And AermodProject0.Aermod.Bprm.ArryBldgi.Length > 0 Then
            strProcess = "正在计算建筑物参数"
            '把污染源参数给建筑物下洗程序
            ReDim AermodProject0.Aermod.Bprm.ArryBuStack(AermodProject0.Aermod.Source.PointSources.PointSource.Length - 1)
            For i As Integer = 0 To AermodProject0.Aermod.Source.PointSources.PointSource.Length - 1
                AermodProject0.Aermod.Bprm.ArryBuStack(i) = New CAermod.BuStack
                AermodProject0.Aermod.Bprm.ArryBuStack(i).BrandName = AermodProject0.Aermod.Source.PointSources.PointSource(i).Location.Srcid
                AermodProject0.Aermod.Bprm.ArryBuStack(i).BrandX = AermodProject0.Aermod.Source.PointSources.PointSource(i).Location.Xs
                AermodProject0.Aermod.Bprm.ArryBuStack(i).BrandY = AermodProject0.Aermod.Source.PointSources.PointSource(i).Location.Ys
                AermodProject0.Aermod.Bprm.ArryBuStack(i).BrandBase = AermodProject0.Aermod.Source.PointSources.PointSource(i).Location.Zs
                AermodProject0.Aermod.Bprm.ArryBuStack(i).BrandHight = AermodProject0.Aermod.Source.PointSources.PointSource(i).Stkhgt
            Next
            If My.Computer.FileSystem.FileExists(CAermod.ModelsPath & "Bpipprm.exe") And My.Computer.FileSystem.FileExists(CAermod.ModelsPath & "bpipprm.BAT") Then
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\Bpipprm.exe") Then
                    My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\Bpipprm.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\Bpipprm.exe")
                End If
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\bpipprm.BAT") Then
                    My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\bpipprm.BAT").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\bpipprm.BAT")
                End If
                My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "Bpipprm.exe", PrjPath & "\" & strNameLast & "\Bpipprm.exe")

                My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "bpipprm.BAT", PrjPath & "\" & strNameLast & "\bpipprm.BAT")
                Dim txtOut As String
                txtOut = AermodProject0.Aermod.Bprm.OutPutBp '获取控制流字符串
                '打开并写入文件。为了防止aermod占用文件，对访问的文件进行多次试试
                Dim IsBusy As Boolean = True
                While IsBusy
                    Try
                        FileOpen(1, PrjPath & "\" & strNameLast & "\" & "bpipprm.inp", OpenMode.Output)
                        IsBusy = False
                    Catch ex As Exception
                        Thread.Sleep(1000)
                    End Try
                End While
                PrintLine(1, txtOut)
                FileClose(1)
                DosCommandOutput = New DosCommand.DosCommandOutput
                DosCommandOutput.CreateNoWindow = True   '是否创建aermod窗体
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "bp.txt") Then
                    '删除存在的SCREEN.OUT和SCREEN.DAT，更新结果
                    My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "bp.txt")
                End If
                DosCommandOutput.Execute(PrjPath & "\" & strNameLast & "\", "bpipprm.BAT", "bp.txt")
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "bp.txt") = False Then
                    MessageBox.Show("建筑物下洗程序不能正确运行!请与作者联系。")
                    Exit Sub
                End If
                '显示结果
                If AermodProject0.Aermod.Bprm.showStr(AermodProject0.SaveName) <> "" AndAlso AermodProject0.Aermod.Bprm.ArryBldgi.Length > 0 Then
                    For i As Integer = 0 To AermodProject0.Aermod.Source.PointSources.PointSource.Length - 1
                        AermodProject0.Aermod.Source.PointSources.PointSource(i).BuildingDownwash = AermodProject0.Aermod.Bprm.ArryBuStack(i).Result '把建筑物的字符串给对应的污染源
                    Next
                Else
                    For i As Integer = 0 To AermodProject0.Aermod.Source.PointSources.PointSource.Length - 1
                        AermodProject0.Aermod.Source.PointSources.PointSource(i).BuildingDownwash = ""
                    Next
                End If
            Else
                MsgBox("建筑物下洗程序不存在，请重新安装程序！或与作者联系！")
                Exit Sub
            End If
        End If

    End Sub


    Private Sub BackgroundWorkerAermod_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorkerAermod.RunWorkerCompleted
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)

        '如果出错，将相应的数据改回来
        If Me.chkRunAermod.Checked = True Then
            AermodProject0.Aermod.MetSource.SurfFile.Name = SurfFileName
            AermodProject0.Aermod.MetSource.ProfFile.Name = ProfFileName
        End If

        DosCommandOutput = Nothing
        Timer1_Tick(sender, e)
        '读取文件结果判断是否运行成功
        If Me.chkRunAermod.Checked = True Then
            Dim StreamToDisplay As StreamReader
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT") Then
                Dim str2 As String = PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT"
                StreamToDisplay = New StreamReader(str2)
                Dim strResult = StreamToDisplay.ReadToEnd
                StreamToDisplay.Close()
                If strResult.Contains("AERMOD Finishes Successfully") = True And m_RusSucess = True Then
                    Me.TextBox1.Text = Me.TextBox1.Text & vbCrLf & "Aermod 程序运行成功!"
                    '把计算的结果赋值给结果类
                    AermodProject0.Iscal = True
                    '设置网格点重新计算
                    AermodProject0.Aermod.Receptor.RecalNest = True '重新计算嵌套网格点
                    '先修改结果文件

                    Me.Status.Text = "计算完毕。"
                    Me.ProgressBar.Visible = False

                    'Dim frmAnalyse As New AnalyseSystem.frmMain
                    'frmAnalyse.ProjectionCollection = Me.ProjectResultCollection
                    'frmAnalyse.ShowDialog()

                Else
                    Me.TextBox1.Text = Me.TextBox1.Text & vbCrLf & "Aermod 程序运行失败!"
                End If
            End If
        End If

        Me.TextBox1.Select(Me.TextBox1.Text.Length, Me.TextBox1.Text.Length)
        Me.TextBox1.ScrollToCaret() '
        '关闭时钟
        Timer1.Stop()
        Me.Status.Text = "正在保存数据。"
        SaveAs()
        Me.cmdRun.Enabled = True
        Me.cmdStop.Enabled = False
        Me.Status.Text = "计算完毕。"
        Me.ProgressBar.Visible = False
    End Sub
    ''' <summary>
    ''' 运行气象预处理程序，并把处理后的数据给aermod
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RunAermet()
        '------------------------------------------------------------------------------------
        '对气象数据进行处理
        '------------------------------------------------------------------------------------
        If AermodProject0.Aermet.Run = True Then
            '在修改字符前删除aermet目录下所有文件
            For Each foundFile As String In My.Computer.FileSystem.GetFiles(AermodProject0.GetProjectPath & "\Aermet\", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
                My.Computer.FileSystem.GetFileInfo(foundFile).Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                My.Computer.FileSystem.DeleteFile(foundFile)
            Next
            If AermodProject0.Aermet.Stage2.MetGeneral.ArrayMetData IsNot Nothing AndAlso AermodProject0.Aermet.Stage2.MetGeneral.ArrayMetData.Length > 0 Then
                strProcess = "正在导出地面气象数据文件"
                Dim MetGen As Met.MetGeneral = AermodProject0.Aermet.Stage2.MetGeneral.Clone
                If MetGen.IsInsert = True Then
                    MetGen.InsetAllMetData()
                End If
                MetGen.ExprotsMetData(AermodProject0.GetProjectPath & "\Aermet\SF.OQA")
                AermodProject0.Aermet.Stage2.MetGeneral.FileName = "Aermet\SF.OQA"
            Else
                MessageBox.Show("请导入地面气象数据!")
                Exit Sub
            End If
            If AermodProject0.Aermet.Stage2.MetUpper.UpMetData.reconnaissance IsNot Nothing AndAlso AermodProject0.Aermet.Stage2.MetUpper.UpMetData.reconnaissance.ArrReconnaissance.Length > 0 Then
                strProcess = "正在导出高空气象数据文件"
                AermodProject0.Aermet.Stage2.MetUpper.UpMetData.ExportData(AermodProject0.GetProjectPath & "\Aermet\UA.OQA")
                AermodProject0.Aermet.Stage2.MetUpper.FileName = "Aermet\UA.OQA"
            Else
                MessageBox.Show("请导入高空气象数据!")
                Exit Sub
            End If
            If AermodProject0.Aermet.Stage2.MetOnSite.OnSiteData.LocaleConcourse.ArrLocaleWeatherData IsNot Nothing AndAlso AermodProject0.Aermet.Stage2.MetOnSite.OnSiteData.LocaleConcourse.ArrLocaleWeatherData.Length > 0 Then
                strProcess = "正在导出现站气象数据文件"
                AermodProject0.Aermet.Stage2.MetOnSite.OnSiteData.ExportData(AermodProject0.GetProjectPath & "\Aermet\OS.OQA")
                AermodProject0.Aermet.Stage2.MetOnSite.FileName = "Aermet\OS.OQA"
            End If
            strProcess = "正在修改气象预处理控制流文件"
            ModifyAermet() '修改控制流文件


            '执行STAGE2程序
            strProcess = "正在合并气象数据文件"
            If My.Computer.FileSystem.FileExists(CAermod.Path.ModelsPath() & "HanAn_Aermet.exe") Then
                If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\HanAn_Aermet.exe") Then
                    My.Computer.FileSystem.GetFileInfo(AermodProject0.GetProjectPath & "\HanAn_Aermet.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(AermodProject0.GetProjectPath & "\HanAn_Aermet.exe")
                End If
                If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\Aermet.exe") Then
                    My.Computer.FileSystem.GetFileInfo(AermodProject0.GetProjectPath & "\Aermet.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(AermodProject0.GetProjectPath & "\Aermet.exe")
                End If
                My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "HanAn_Aermet.exe", AermodProject0.GetProjectPath & "\HanAn_Aermet.exe")
                My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "Aermet.exe", AermodProject0.GetProjectPath & "\Aermet.exe")

                If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\aermet.inp") Then
                    My.Computer.FileSystem.GetFileInfo(AermodProject0.GetProjectPath & "\aermet.inp").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(AermodProject0.GetProjectPath & "\aermet.inp")
                End If
                My.Computer.FileSystem.CopyFile(AermodProject0.GetProjectPath & "\Aermet\stage2.inp", AermodProject0.GetProjectPath & "\aermet.inp")
                DosCommandOutput = New DosCommand.DosCommandOutput
                DosCommandOutput.CreateNoWindow = 1 '是否创建HanAn_Aermet.exe窗体
                If AermodProject0.Aermet.AermetProgram = 0 Then '东半球，并且采用EPA的程序进行计算
                    DosCommandOutput.Execute(AermodProject0.GetProjectPath & "\", "Aermet.exe", "Aermet\1.txt")
                Else
                    DosCommandOutput.Execute(AermodProject0.GetProjectPath & "\", "HanAn_Aermet.exe", "Aermet\1.txt")
                End If
                If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\" & "Aermet\" & "1.txt") Then
                    Dim StreamToDisplay As StreamReader
                    Dim str1 As String = AermodProject0.GetProjectPath & "\" & "Aermet\" & "1.txt"
                    StreamToDisplay = New StreamReader(str1)
                    Dim txtReslut = StreamToDisplay.ReadToEnd
                    StreamToDisplay.Close()
                    If txtReslut.Contains("AERMET Data Processing Finished Successfully") = False Then
                        MessageBox.Show("程序运行失败!请检查预测方案。", "运行失败")
                        ShowStage2Error()
                        Exit Sub
                    End If

                End If
            Else
                If AermodProject0.Aermet.AermetProgram = 0 Then '东半球，并且采用EPA的程序进行计算
                    MsgBox("无法找到Aermet.exe文件,请重新安装软件。")
                Else
                    MsgBox("无法找到HanAn_Aermet.exe文件,请重新安装软件。")
                End If
            End If
            '执行STAGE3程序
            strProcess = "正在生成气象数据文件"
            If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\" & "HanAn_Aermet.exe") Then

                If My.Computer.FileSystem.FileExists(AermodProject0.GetProjectPath & "\" & "aermet.inp") Then
                    My.Computer.FileSystem.GetFileInfo(AermodProject0.GetProjectPath & "\" & "aermet.inp").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(AermodProject0.GetProjectPath & "\" & "aermet.inp")
                End If
                My.Computer.FileSystem.CopyFile(AermodProject0.GetProjectPath & "\" & "Aermet\" & "stage3.inp", AermodProject0.GetProjectPath & "\" & "aermet.inp")
                DosCommandOutput = New DosCommand.DosCommandOutput
                DosCommandOutput.CreateNoWindow = 1 '是否创建HanAn_Aermet.exe窗体

                If AermodProject0.Aermet.AermetProgram = 0 Then '东半球，并且采用EPA的程序进行计算

                    DosCommandOutput.Execute(AermodProject0.GetProjectPath & "\", "Aermet.exe", "Aermet\1.txt")
                Else
                    DosCommandOutput.Execute(AermodProject0.GetProjectPath & "\", "HanAn_Aermet.exe", "Aermet\1.txt")
                End If
            Else
                If AermodProject0.Aermet.AermetProgram = 0 Then '东半球，并且采用EPA的程序进行计算
                    MsgBox("无法找到Aermet.exe文件。")
                Else
                    MsgBox("无法找到HanAn_Aermet.exe文件。")
                End If
            End If
            AermodProject0.Aermod.MetSource.SurfFile.Name = "Aermet\aemodSurf.SFC"
            AermodProject0.Aermod.MetSource.SurfFile.LoadMetData(AermodProject0.GetProjectPath & "\" & AermodProject0.Aermod.MetSource.SurfFile.Name)
            AermodProject0.Aermod.MetSource.ProfFile.Name = "Aermet\aemodProf.PFL"
            AermodProject0.Aermod.MetSource.SelectedMetFile = False
        End If
    End Sub

    ''' <summary>
    ''' 根据用户设置的方案创建相应的目录
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CreateProjFolder()
        With PublicVal.AermodProject0.ProjSetCollection
            For i As Integer = 0 To .Count - 1
                If .Item(i).Selected = True Then
                    Try
                        If .Item(i).Selected = True Then
                            If My.Computer.FileSystem.DirectoryExists(AermodProject0.GetProjectPath & "\aermod\" & .Item(i).ID) = True Then
                                My.Computer.FileSystem.DeleteDirectory(AermodProject0.GetProjectPath & "\aermod\" & .Item(i).ID, FileIO.DeleteDirectoryOption.DeleteAllContents)
                            End If
                            Dim strFolder As String = AermodProject0.GetProjectPath & "\aermod\" & .Item(i).ID
                            My.Computer.FileSystem.CreateDirectory(AermodProject0.GetProjectPath & "\aermod\" & .Item(i).ID)
                        End If
                    Catch ex As Exception
                        MessageBox.Show(ex.Message)
                    End Try
                End If
            Next
        End With

    End Sub
    Private Function SaveAs() As Boolean
        Me.Status.Text = "正在保存文件"
        Try
            Dim SaveFileDialog1 As New SaveFileDialog
            Dim sFile As String
            Dim strNameLast As String
            sFile = AermodProject0.SaveName
            ' To write to a file, create a StreamWriter object.
            strNameLast = CAermod.GetFileName(sFile)
            AermodProject0.SaveName = sFile
            AermodProject0.IsSaved = True

            '保存主项目文件------------------------------
            Dim fileStr As Stream = File.Open(sFile, FileMode.Create)
            Dim formatter As IFormatter
            formatter = CType(New BinaryFormatter, IFormatter)
            formatter.Serialize(fileStr, PublicVal.AermodProject0)
            fileStr.Dispose()
            ' All done
            fileStr.Close()

            Try
                fileStr = File.Open(sFile, FileMode.Open)

                formatter = CType(New BinaryFormatter, IFormatter)
                fileStr.Seek(0, SeekOrigin.Begin)
                Dim obj As Object = formatter.Deserialize(fileStr)
                ' All done
                fileStr.Close()
            Catch ex As Exception
                fileStr.Close()
                MsgBox("保存文件时出现意外错误，请重新保存!")
                Return False
            End Try
            '------------------------------
            Return True
        Catch ex As Exception
            MsgBox("保存文件时出现意外错误，请重新保存!")
            Return False
        End Try
    End Function
    Private Sub RunAermodProject()
        '创建项目对应的文件夹
        CreateProjFolder()


        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)
        Try
            '修改地面气象数据文件
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodSurf.SFC") Then
                My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodSurf.SFC").Attributes = FileAttributes.Normal '设置文件的属性为常规，以便于删除
                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodSurf.SFC")
            End If
            If AermodProject0.Aermod.MetSource.SelectedMetFile = True And AermodProject0.Aermod.MetSource.SurfFile.Name <> "" Then
                My.Computer.FileSystem.CopyFile(AermodProject0.Aermod.MetSource.SurfFile.Name, PrjPath & "\" & strNameLast & "\" & "Aermod\aemodSurf.SFC")
            Else
                My.Computer.FileSystem.CopyFile(AermodProject0.GetProjectPath & "\Aermet\aemodSurf.SFC", PrjPath & "\" & strNameLast & "\" & "Aermod\aemodSurf.SFC")
            End If
            SurfFileName = AermodProject0.Aermod.MetSource.SurfFile.Name
            AermodProject0.Aermod.MetSource.SurfFile.Name = "Aermod\aemodSurf.SFC"
        Catch ex As Exception
            MsgBox("请导入地面气象数据文件")
            Exit Sub
        End Try
        Try
            '修改垂直气象数据文件
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodProf.PFL") Then
                My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodProf.PFL").Attributes = FileAttributes.Normal '设置文件的属性为常规，以便于删除
                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "Aermod\aemodProf.PFL")
            End If
            If AermodProject0.Aermod.MetSource.SelectedMetFile = True And AermodProject0.Aermod.MetSource.ProfFile.Name <> "" Then
                My.Computer.FileSystem.CopyFile(AermodProject0.Aermod.MetSource.ProfFile.Name, PrjPath & "\" & strNameLast & "\" & "Aermod\aemodProf.PFL")
            Else
                My.Computer.FileSystem.CopyFile(AermodProject0.GetProjectPath & "\Aermet\aemodProf.PFL", PrjPath & "\" & strNameLast & "\" & "Aermod\aemodProf.PFL")
            End If
            ProfFileName = AermodProject0.Aermod.MetSource.ProfFile.Name
            AermodProject0.Aermod.MetSource.ProfFile.Name = "Aermod\aemodProf.PFL"
        Catch ex As Exception
            MsgBox("请导入廓线气象数据文件")
            Exit Sub
        End Try
        '-----------------------------------------------------
        '检查污染源是否都为0
        '-----------------------------------------------------
        For i As Integer = 0 To AermodProject0.Aermod.Control.AllPolluts.AllSelectPollut.Length - 1
            If AermodProject0.Aermod.Source.GetAllRate(AermodProject0.Aermod.Control, i) = False Then
                MessageBox.Show("所有污染源" & AermodProject0.Aermod.Control.AllPolluts.AllSelectPollut(i).Name & "的排放速率均为0，请重新设置。如果您已经在控制选项中选择了这个污染物，同时应设置其在污染源中的排放速率。")
                Exit Sub
            End If
        Next






        If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\aermod.exe") Then
            My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\aermod.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
            My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\aermod.exe")
        End If
        My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "aermod09292.exe", PrjPath & "\" & strNameLast & "\aermod.exe")
        '---------------------------------------------------------------------------------------------
        '把运行设置为NOT，检查运行方案
        '---------------------------------------------------------------------------------------------
        For i As Integer = 0 To ListProj.Items.Count - 1
            If Me.ListProj.GetItemChecked(i) = True Then '如果选中该方案就计算该方案
                AermodProject0.ProjSetCollection.Item(i).IsSavedResult = False '设置方案结果为未保存

                '-----------------------------------------------------------------------------------------------------------------------------------------------
                AermodProject0.ProjSetCollection.Item(i).SetTempAermod(AermodProject0.Aermod.Clone, PrjPath & "\" & strNameLast)
                '输出inp文件的字符串
                Dim txtOut As String = AermodProject0.ProjSetCollection.Item(i).TempAermod.OutPutAermod(0, AermodProject0.ProjSetCollection.Item(i).ID)
                strProcess = AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "浓度"
                '打开并写入文件。为了防止aermod占用文件，对访问的文件进行多次试试
                Dim IsBusy As Boolean
                Try
                    FileOpen(1, PrjPath & "\" & strNameLast & "\" & "aermod.inp", OpenMode.Output)
                    IsBusy = False
                Catch ex As Exception
                    Thread.Sleep(1000)
                    IsBusy = True
                End Try
                While IsBusy
                    Try
                        FileOpen(1, PrjPath & "\" & strNameLast & "\" & "aermod.inp", OpenMode.Output)
                        IsBusy = False
                    Catch ex As Exception
                        Thread.Sleep(1000)
                    End Try
                End While
                PrintLine(1, txtOut)
                FileClose(1)
                DosCommandOutput = New DosCommand.DosCommandOutput
                DosCommandOutput.CreateNoWindow = Not sCreateAermodWindow '是否创建aermod窗体
                DosCommandOutput.Execute(PrjPath & "\" & strNameLast & "\", "aermod.exe", "tmp\1.txt")

                '读取文件结果判断是否运行成功
                Dim StreamToDisplay As StreamReader
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT") Then
                    Dim str2 As String = PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT"
                    StreamToDisplay = New StreamReader(str2)
                    Dim strResult = StreamToDisplay.ReadToEnd
                    StreamToDisplay.Close()
                    If strResult.Contains("AERMOD Finishes Successfully") = False Then
                        MessageBox.Show("Aermod程序运行失败，请检查您的预测方案!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Dim dlgError As New dlgError
                        dlgError.RichTextBox1.Text = AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "方案出错!" & vbCrLf & CAermod.StringHandle.GetAermodError(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT")
                        dlgError.ShowDialog()
                        Exit Sub
                    End If
                End If

               
            End If
        Next

        '检查方案结束


        '--------------------------------------------------------------------------------------
        '运行Aermod程序 
        '--------------------------------------------------------------------------------------

        '执行aermod程序
        If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "aermod.exe") Then


            '设置计算结果数组
            For i As Integer = 0 To Me.ListProj.Items.Count - 1
                If Me.ListProj.GetItemChecked(i) = True Then '如果选中该方案就计算该方案
                    AermodProject0.ProjSetCollection.Item(i).SetTempAermod(AermodProject0.Aermod.Clone, PrjPath & "\" & strNameLast) '重新设置项目所对应的方案
                    AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.Run = True
                    'AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod = AermodProject0.ProjSetCollection.Item(i).TempAermod.Clone
                    'ReDim AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod.AermodResultsPollute(AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod.Control.AllPolluts.AllSelectPollut.Length - 1)
                    'For ni As Integer = 0 To AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod.AermodResultsPollute.Length - 1 '实例化计算结果
                    '    AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod.AermodResultsPollute(ni) = New CAermod.AermodResultsPollute
                    'Next
                    '--------------------------------------------------------------------------------------
                    '输出Aermod运行方案
                    '--------------------------------------------------------------------------------------
                    Dim txtOut As String
                    txtOut = AermodProject0.ProjSetCollection.Item(i).TempAermod.OutPutAermod(0, AermodProject0.ProjSetCollection.Item(i).ID)
                    '把方案复制到相应的目录下
                    FileOpen(1, PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "_控制流文件.inp", OpenMode.Output)
                    PrintLine(1, txtOut)
                    FileClose(1)

                    strProcess = "正在计算" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "浓度"
                    '打开并写入文件。为了防止aermod占用文件，对访问的文件进行多次试试
                    Dim IsBusy As Boolean
                    Try
                        FileOpen(1, PrjPath & "\" & strNameLast & "\" & "aermod.inp", OpenMode.Output)
                        IsBusy = False
                    Catch ex As Exception
                        Thread.Sleep(1000)
                        IsBusy = True
                    End Try
                    While IsBusy
                        Try
                            FileOpen(1, PrjPath & "\" & strNameLast & "\" & "aermod.inp", OpenMode.Output)
                            IsBusy = False
                        Catch ex As Exception
                            Thread.Sleep(1000)
                        End Try
                    End While
                    PrintLine(1, txtOut)
                    FileClose(1)
                    DosCommandOutput = New DosCommand.DosCommandOutput
                    DosCommandOutput.CreateNoWindow = Not sCreateAermodWindow '是否创建aermod窗体
                    DosCommandOutput.Execute(PrjPath & "\" & strNameLast & "\", "aermod.exe", "tmp\1.txt")

                    '读取文件结果判断是否运行成功
                    Dim StreamToDisplay As StreamReader
                    If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT") Then
                        Dim str2 As String = PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT"
                        StreamToDisplay = New StreamReader(str2)
                        Dim strResult = StreamToDisplay.ReadToEnd
                        StreamToDisplay.Close()
                        AermodProject0.ProjSetCollection.Item(i).TempAermod.IsRuned = True
                        If strResult.Contains("AERMOD Finishes Successfully") = False Then
                            MessageBox.Show("Aermod程序运行失败，请检查您的预测方案!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Dim dlgError As New dlgError
                            dlgError.RichTextBox1.Text = CAermod.StringHandle.GetAermodError(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT")
                            dlgError.ShowDialog()
                            Exit Sub
                        Else
                            '把结果文件复制到Aermod目录下：
                            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.Aermod.Control.AllPolluts.AllSelectPollut(0).Name & "_AERMOD.OUT") Then
                                My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.Aermod.Control.AllPolluts.AllSelectPollut(0).Name & "_AERMOD.OUT").Attributes = FileAttributes.Normal '设置文件的属性为常规，以便于删除
                                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.Aermod.Control.AllPolluts.AllSelectPollut(0).Name & "_AERMOD.OUT")
                            End If
                            My.Computer.FileSystem.CopyFile(PrjPath & "\" & strNameLast & "\" & "AERMOD.OUT", PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "_输出文件.OUT")
                            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "HourEmis.txt") Then
                                My.Computer.FileSystem.CopyFile(PrjPath & "\" & strNameLast & "\" & "HourEmis.txt", PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "_HourEmis.txt")
                            End If


                        End If
                        '下面的代码把方案保存到项目的文件夹中，并取名TempAermod.aer。在预测计算完成后，需要再反序列化该文件。这样做主要是为了减少主文件的大小和降低内存消耗。
                        Dim strTempName As String = PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ID & "\" & "TempAermod.aer" '获得保存结果方案文件的文件名
                        '保存主项目文件------------------------------
                        Dim fileStr As Stream = File.Open(strTempName, FileMode.Create)
                        Dim formatter As IFormatter
                        Try
                            formatter = CType(New BinaryFormatter, IFormatter)
                            formatter.Serialize(fileStr, AermodProject0.ProjSetCollection.Item(i).TempAermod) '保存方案文件中的aermod
                            fileStr.Dispose()
                            fileStr.Close()
                        Catch ex As Exception
                            fileStr.Dispose()
                            fileStr.Close()
                            MsgBox("在序列化方案文件时出现意外错误!")
                            Exit Sub
                        End Try
                    End If

                    '------------------------------
                    '将输出文件的名称给数组
                    strProcess = "正在对" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "浓度进行分析"
                    'If AermodProject0.ProjSetCollection.Item(i).ProjResult.TempAermod.GetData(PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ProjName & "\" & AermodProject0.ProjSetCollection.Item(i).TempAermod.Control.AllPolluts.AllSelectPollut(0).Name & "_输出文件.OUT" _
                    '                                                                          , 0, PrjPath & "\" & strNameLast & "\" & "Aermod\" & AermodProject0.ProjSetCollection.Item(i).ProjName & "\", PrjPath & "\" & strNameLast & "_Result\" & AermodProject0.ProjSetCollection.Item(i).ProjName & "\") = False Then
                    '    Exit Sub
                    'End If
                    '设置等值线
                    '在完成序列化文件后，要释放内在空间。
                    AermodProject0.ProjSetCollection.Item(i).TempAermod = Nothing

                End If
            Next
        End If
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)
        Dim StreamToDisplay As StreamReader
        Me.Status.Text = strProcess
        If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "tmp\1.txt") Then
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "tmp\2.txt") Then
                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "tmp\2.txt")
            End If
            My.Computer.FileSystem.CopyFile(PrjPath & "\" & strNameLast & "\" & "tmp\1.txt", PrjPath & "\" & strNameLast & "\" & "tmp\2.txt")
            Dim str2 As String = PrjPath & "\" & strNameLast & "\" & "tmp\2.txt"
            StreamToDisplay = New StreamReader(str2)
            Me.TextBox1.Text = StreamToDisplay.ReadToEnd
            StreamToDisplay.Close()
            Me.TextBox1.Select(Me.TextBox1.Text.Length, Me.TextBox1.Text.Length)
            Me.TextBox1.ScrollToCaret() '
        End If
    End Sub
    ''' <summary>
    ''' 修改第个控制流文件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ModifyAermet()
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)

        '修改第二步控制流文件
        Dim txtOut As String
        txtOut = AermodProject0.Aermet.Stage2.OutPutStage2
        '打开并写入文件
        FileOpen(1, PrjPath & "\" & strNameLast & "\Aermet\stage2.inp", OpenMode.Output)
        PrintLine(1, txtOut)
        FileClose(1)
        '修改第三步控制流文件
        '用于储存预测方案中的坐标
        Dim OldLongitude As Double = AermodProject0.Aermet.Stage2.MetGeneral.Location.Longitude.Number
        Dim OldDir As Integer = AermodProject0.Aermet.Stage2.MetGeneral.Location.Longitude.Dir
        Dim OldTadjust As Integer = AermodProject0.Aermet.Stage2.MetGeneral.Location.Tadjust
        '对于东半球的气象处理要修改经度的坐标和时区
        If AermodProject0.Aermet.Stage3.Location.Longitude.Dir = 0 And AermodProject0.Aermet.AermetProgram = 0 Then '东半球，并且采用EPA的程序进行计算
            AermodProject0.Aermet.Stage3.Location.Longitude.Number = 180 - AermodProject0.Aermet.Stage3.Location.Longitude.Number
            AermodProject0.Aermet.Stage3.Location.Longitude.Dir = 1
            AermodProject0.Aermet.Stage3.Location.Tadjust = AermodProject0.Aermet.Stage3.Location.Tadjust + 12
        End If
        txtOut = AermodProject0.Aermet.Stage3.QutPutStage3
        '打开并写入文件
        FileOpen(1, PrjPath & "\" & strNameLast & "\Aermet\stage3.inp", OpenMode.Output)
        PrintLine(1, txtOut)
        FileClose(1)
        '把修改后的坐标再改回来
        AermodProject0.Aermet.Stage3.Location.Longitude.Number = OldLongitude
        AermodProject0.Aermet.Stage3.Location.Longitude.Dir = OldDir
        AermodProject0.Aermet.Stage3.Location.Tadjust = OldTadjust
    End Sub

    Private Function RunAermap() As Boolean

        strProcess = "正在计算地形参数"
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)

        ''先删除tmp下的所有文件
        'For Each foundFile As String In My.Computer.FileSystem.GetFiles(PrjPath & "\" & strNameLast & "\" & "Aermap\", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
        '    Try
        '        My.Computer.FileSystem.GetFileInfo(foundFile).Attributes = FileAttributes.Normal '设置文件的属性为常规，以便于删除
        '        My.Computer.FileSystem.DeleteFile(foundFile)
        '    Catch ex As Exception

        '    End Try
        'Next
        Dim OldFilePath(-1) As String
        For i As Integer = 0 To AermodProject0.Aermap.Control.DataFile.Length - 1
            Try
                '修改地面数据文件
                If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM") Then
                    My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM").Attributes = FileAttributes.Normal '设置文件的属性为常规，以便于删除
                    My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM")
                End If
                My.Computer.FileSystem.CopyFile(AermodProject0.GetProjectPath & "\aermap\" & AermodProject0.Aermap.Control.DataFile(i) & ".dem", PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM")
                ReDim Preserve OldFilePath(OldFilePath.Length)
                OldFilePath(OldFilePath.Length - 1) = AermodProject0.Aermap.Control.DataFile(i)
                AermodProject0.Aermap.Control.DataFile(i) = "Aermap\" & i & ".DEM"
                If AermodProject0.Aermap.AermapProgram = 0 And AermodProject0.Aermap.Control.AnchorXY.Zautm >= 30 Then
                    Dim newdem As New DemManager.DemManage
                    newdem.ReadDEM(PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM")
                    If AermodProject0.Aermap.Control.DataType = 1 Then
                        newdem.Zone = newdem.Zone - 30
                    Else
                        newdem.CoordinatesSW.x = newdem.CoordinatesSW.x - 180 * 3600
                        newdem.CoordinatesSE.x = newdem.CoordinatesSE.x - 180 * 3600
                        newdem.CoordinatesNW.x = newdem.CoordinatesNW.x - 180 * 3600
                        newdem.CoordinatesNE.x = newdem.CoordinatesNE.x - 180 * 3600
                    End If
                    newdem.WriteDEM(PrjPath & "\" & strNameLast & "\" & "Aermap\" & i & ".DEM")
                End If
            Catch ex As Exception
                MsgBox("请导入高程数据文件")
                Return False
            End Try
        Next

        '设置污染源
        AermodProject0.Aermap.Source.Sources = AermodProject0.Aermod.Source.Clone '设置点源
        '设置接受点
        AermodProject0.Aermap.Receptor.DiscCarts = AermodProject0.Aermod.Receptor.DiscCarts
        AermodProject0.Aermap.Receptor.SubGridCart(0) = AermodProject0.Aermod.Receptor.SubGridCart(0)
        '为了重新计算Evel、Hill、flag等，要重新设置参数。
        AermodProject0.Aermap.Receptor.SubGridCart(0).ElevSelected = False
        AermodProject0.Aermap.Receptor.SubGridCart(0).HillSelected = False
        AermodProject0.Aermap.Receptor.SubGridCart(0).FlagSelected = False
        '设置嵌套网格
        AermodProject0.Aermap.Receptor.SubGridCart = AermodProject0.Aermod.Receptor.SubGridCart
        If AermodProject0.Aermap.Receptor.SubGridCart IsNot Nothing Then
            For i As Integer = 0 To AermodProject0.Aermap.Receptor.SubGridCart.Length - 1
                AermodProject0.Aermap.Receptor.SubGridCart(i).ElevSelected = False
                AermodProject0.Aermap.Receptor.SubGridCart(i).HillSelected = False
                AermodProject0.Aermap.Receptor.SubGridCart(i).FlagSelected = False
            Next
        End If

        '执行aermap程序
        If My.Computer.FileSystem.FileExists(CAermod.ModelsPath & "aermap06341.exe") And My.Computer.FileSystem.FileExists(CAermod.ModelsPath & "aermap09040.exe") Then
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\aermap06341.exe") Then
                My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\aermap06341.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\aermap06341.exe")
            End If
            If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\aermap09040.exe") Then
                My.Computer.FileSystem.GetFileInfo(PrjPath & "\" & strNameLast & "\aermap09040.exe").Attributes = IO.FileAttributes.Normal '设置文件的属性为常规，以便于删除
                My.Computer.FileSystem.DeleteFile(PrjPath & "\" & strNameLast & "\aermap09040.exe")
            End If
            My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "aermap06341.exe", PrjPath & "\" & strNameLast & "\aermap06341.exe")
            My.Computer.FileSystem.CopyFile(CAermod.Path.ModelsPath() & "aermap09040.exe", PrjPath & "\" & strNameLast & "\aermap09040.exe")

            '修改DEM坐标平移------------------------------------------------------------
            Dim OldZautm As Integer = AermodProject0.Aermap.Control.AnchorXY.Zautm
            Dim OldZonMax As Integer = AermodProject0.Aermap.Control.DomainXY.Zonmax
            Dim OldZonmin As Integer = AermodProject0.Aermap.Control.DomainXY.Zonmin
            If AermodProject0.Aermap.AermapProgram = 0 And OldZautm >= 30 Then
                AermodProject0.Aermap.Control.AnchorXY.Zautm = OldZautm - 30
                AermodProject0.Aermap.Control.DomainXY.Zonmax = OldZonMax - 30
                AermodProject0.Aermap.Control.DomainXY.Zonmin = OldZonmin - 30
            End If
            '-------------------------------------------------------------------------
            '打开并写入文件。为了防止aermod占用文件，对访问的文件进行多次试试
            Dim txtOut As String
            txtOut = AermodProject0.Aermap.OutPutAermap(AermodProject0.Aermod.Control)
            '打开并写入文件
            FileOpen(1, PrjPath & "\" & strNameLast & "\" & "aermap.inp", OpenMode.Output)
            PrintLine(1, txtOut)
            FileClose(1)
            DosCommandOutput = New DosCommand.DosCommandOutput
            DosCommandOutput.CreateNoWindow = Not sCreateAermodWindow '是否创建aermap窗体

            If AermodProject0.Aermap.AermapProgram = 0 Then
                DosCommandOutput.Execute(PrjPath & "\" & strNameLast & "\", "aermap09040.exe", "tmp\1.txt")
            Else
                DosCommandOutput.Execute(PrjPath & "\" & strNameLast & "\", "aermap09040.exe", "tmp\1.txt")
            End If
            AermodProject0.Aermap.Control.AnchorXY.Zautm = OldZautm
            AermodProject0.Aermap.Control.DomainXY.Zonmax = OldZonMax
            AermodProject0.Aermap.Control.DomainXY.Zonmin = OldZonmin
            '判断设置的污染源和接受点区域是否在DEM数据范围之内
            If AermodProject0.Aermap.IsInBand = False Then
                '程序执行完成后将相应的数据改回来
                For i As Integer = 0 To AermodProject0.Aermap.Control.DataFile.Length - 1
                    AermodProject0.Aermap.Control.DataFile(i) = OldFilePath(OldFilePath.Length - 1)
                Next
                Return False
            End If
        Else
            MessageBox.Show("找不到aermap06341.exe文件，请重新安装程序或与作者联系!", "执行aermap错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            '程序执行完成后将相应的数据改回来
            For i As Integer = 0 To AermodProject0.Aermap.Control.DataFile.Length - 1
                AermodProject0.Aermap.Control.DataFile(i) = OldFilePath(OldFilePath.Length - 1)
            Next
            Return False
        End If
        '程序执行完成后将相应的数据改回来
        For i As Integer = 0 To AermodProject0.Aermap.Control.DataFile.Length - 1
            AermodProject0.Aermap.Control.DataFile(i) = OldFilePath(OldFilePath.Length - 1)
        Next

        '读取文件结果判断是否运行成功
        Dim StreamToDisplay As StreamReader
        If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "AERMAP.OUT") Then
            Dim str2 As String = PrjPath & "\" & strNameLast & "\" & "AERMAP.OUT"
            StreamToDisplay = New StreamReader(str2)
            Dim strResult = StreamToDisplay.ReadToEnd
            StreamToDisplay.Close()
            If strResult.Contains("AERMAP Finishes Successfully") = True Then
                '程序运行完成后相应的修改污染源和接受点的高程坐标
                strProcess = "正在将地形参数导入到Aermod中"
                AermodProject0.Aermod = CAermod.Tarrern.ImPortsAermap(AermodProject0.Aermod, PrjPath & "\" & strNameLast & "\Aermap\Srcfile.src", PrjPath & "\" & strNameLast & "\Aermap\Recfil.rec")
                Return True
            Else
                MessageBox.Show("AERMAP程序运行失败，请检查您的预测方案!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Dim dlgError As New dlgError
                dlgError.RichTextBox1.Text = CAermod.StringHandle.GetAermapError(PrjPath & "\" & strNameLast & "\" & "AERMAP.OUT")
                dlgError.ShowDialog()
                Return False
            End If
        End If

        Return False
    End Function
    Private Sub ShowStage2Error()
        Dim PrjPath As String = My.Computer.FileSystem.GetFileInfo(AermodProject0.SaveName).DirectoryName
        Dim strNameLast As String = CAermod.GetFileName(AermodProject0.SaveName)

        If My.Computer.FileSystem.FileExists(PrjPath & "\" & strNameLast & "\" & "Aermet\" & "EX05_S2.ERR") Then
            Dim frmE As New AermetSystem.frmEdit
            Dim fs As New FileStream(PrjPath & "\" & strNameLast & "\" & "Aermet\" & "EX05_S2.ERR", FileMode.Open)
            Dim sr As New StreamReader(fs)
            Dim str As String
            str = sr.ReadToEnd.ToString
            sr.Close()
            fs.Close()
            frmE.TextBox1.Text = str
            frmE.ShowDialog()
        Else
            MsgBox("文件不存在，请运行程序后再查看!")
        End If
    End Sub


    ''' <summary>
    ''' 终止DOS程序的进程
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StopProcess()
        '创建一个Process类型的数组
        Dim pTemp As System.Diagnostics.Process()
        '通过此语句返回的是进程数组，这些进程数组存放的是当前运行存在地进程资源
        pTemp = System.Diagnostics.Process.GetProcesses()
        '获取计算机中每一个进程的信息，并显示出来
        Dim pTempProcess As System.Diagnostics.Process
        For Each pTempProcess In pTemp
            '得到进程的名称
            Dim sProcessNeme As String = pTempProcess.ProcessName
            '得到进程的ID号
            Dim sProcessID As String = pTempProcess.Id.ToString()
            '得到进程的开始运行时间
            'Dim sStartTime As String = pTempProcess.StartTime.ToString()
            '得到进程运行所需要的内存大小
            Dim sMemroyUse As String = pTempProcess.PrivateMemorySize64.ToString()
            If sProcessNeme.ToUpper = "AERMOD" Then
                Try
                    Dim pProcessTemp As System.Diagnostics.Process = Process.GetProcessById(sProcessID)
                    '杀死此进程 
                    pProcessTemp.Kill()
                    pProcessTemp.Close()
                Catch ex As Exception

                End Try

            End If
            If sProcessNeme.ToUpper.Contains("AERMAP") Then
                Try
                    Dim pProcessTemp As System.Diagnostics.Process = Process.GetProcessById(sProcessID)
                    '杀死此进程 
                    pProcessTemp.Kill()
                    pProcessTemp.Close()
                Catch ex As Exception

                End Try

            End If
        Next
    End Sub

    Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
        StopProcess()
    End Sub

   
    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub
End Class
